<?php
/**
 *  Application middleware
 * @var $app Slim\App
 * @var $container Slim\Container
 */

use Slim\Http\Request;
use Slim\Http\Response;

// Slim 处理带有斜线结尾的 URL 和不带斜线的 URL 的方式不同。意思就是 /user 和 /user/ 不是一回事，它们可以有不同的回调。
// redirect '/user/' to '/user'
$app->add(function (Request $request, Response $response, callable $next) {
    $uri = $request->getUri();
    $path = $uri->getPath();
    if ($path !== '/' && substr($path, -1) === '/') {
        // permanently redirect paths with a trailing slash
        // to their non-trailing counterpart
        $uri = $uri->withPath(substr($path, 0, -1));
        return $response->withRedirect((string)$uri, 301);
    }

    return $next($request, $response);
});

// enable Csrf Token
if ( \Slim::get('settings')['enableCsrfToken'] ) {
    $app->add( $container->get('csrf') );
}

// add debug tool : Whoops
if ( \Slim::get('settings')['debug'] ) {
    $app->add(new \inhere\whoops\middleware\WhoopsTool());
}

$app->add(function(Request $request, Response $response, callable $next) {
    // Use the PSR 7 $response object
// de($request->getUri());
    // Sample log message
    $this->logger->info('Slim-Skeleton \''.$request->getServerParams()['REQUEST_URI'].'\' route', $request->getParams());

    // set css theme by cookie
    if ( !empty($request->getCookieParams()['css_style']) ) {
        $cssStyle = $request->getCookieParams()['css_style'];
        $cssFile = \Slim::alias('@assets/libs/bootswatch') . "/$cssStyle/bootstrap.min.css";

        if ( file_exists($cssFile) ) {
            \Slim::get('pageSet')->set('cssStyle', $cssStyle);
        }
    }

    return $next($request, $response);
});
